package com.heima.news.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitMQConfig {

    public static final String DELAY_EXCHANGE = "delay.direct";
    public static final String DELAY_QUEUE = "delay.queue";
    public static final String DELAY_ROUTING_KEY = "delay.key";
    // 定义交换机名称
    public static final String NEWS_EXCHANGE = "news.exchange";

    // 定义队列名称
    public static final String NEWS_INSERT_QUEUE = "news.insert.queue";
    public static final String NEWS_UPDATE_QUEUE = "news.update.queue";
    public static final String NEWS_DELETE_QUEUE = "news.delete.queue";

    // 定义路由键
    public static final String NEWS_INSERT_KEY = "news.insert.key";
    public static final String NEWS_UPDATE_KEY = "news.update.key";
    public static final String NEWS_DELETE_KEY = "news.delete.key";

    /**
     * 延迟 Exchange（类型 x-delayed-message）
     */
    @Bean
    public CustomExchange delayExchange() {
        Map<String, Object> args = new HashMap<>();
        args.put("x-delayed-type", "direct");
        return new CustomExchange(DELAY_EXCHANGE, "x-delayed-message", true, false, args);
    }

    /**
     * 延迟队列
     */
    @Bean
    public Queue delayQueue() {
        return QueueBuilder.durable(DELAY_QUEUE).build();
    }

    /**
     * 绑定
     */
    @Bean
    public Binding delayBinding() {
        return BindingBuilder
                .bind(delayQueue())
                .to(delayExchange())
                .with(DELAY_ROUTING_KEY)
                .noargs();
    }

    /**
     * 配置 RabbitTemplate 支持消息确认（可选）
     */
    @Bean
    public RabbitTemplate rabbitTemplate(CachingConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        // 启用回调（可加日志）
        template.setMandatory(true);
        return template;
    }
    @Bean
    public DirectExchange newsExchange() {
        return new DirectExchange(NEWS_EXCHANGE);
    }

    @Bean
    public Queue newsInsertQueue() {
        return new Queue(NEWS_INSERT_QUEUE);
    }

    @Bean
    public Queue newsUpdateQueue() {
        return new Queue(NEWS_UPDATE_QUEUE);
    }

    @Bean
    public Queue newsDeleteQueue() {
        return new Queue(NEWS_DELETE_QUEUE);
    }

    @Bean
    public Binding bindingInsert() {
        return BindingBuilder.bind(newsInsertQueue()).to(newsExchange()).with(NEWS_INSERT_KEY);
    }

    @Bean
    public Binding bindingUpdate() {
        return BindingBuilder.bind(newsUpdateQueue()).to(newsExchange()).with(NEWS_UPDATE_KEY);
    }

    @Bean
    public Binding bindingDelete() {
        return BindingBuilder.bind(newsDeleteQueue()).to(newsExchange()).with(NEWS_DELETE_KEY);
    }
}
